package vip.finance.makemoney.config.interceptor;

import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import vip.finance.makemoney.common.RestEnum;
import vip.finance.makemoney.common.WebJson;
import vip.finance.makemoney.common.vo.UserInfo;
import vip.finance.makemoney.config.UserContext;
import vip.finance.makemoney.config.UserContextManager;
import vip.finance.makemoney.config.annotation.NoAuth;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 功能描述:  拦截
 *
 * @author : 杨滨
 * @version : v2.6.0
 * @return :
 * @date : 2019/4/29 20:37
 */
@Slf4j
@Configuration
public class UserPermissionInterceptor implements HandlerInterceptor {

    @Resource
    private UserContextManager userContextManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        log.info("requestURI：{}", request.getRequestURI());

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod handlerMethod)) {
            return true;
        }
        // 获取方法上的注解
        Method method = handlerMethod.getMethod();

        //检查是否有注释，有则跳过认证
        if (method.isAnnotationPresent(NoAuth.class)) {
            return true;
        }
        UserInfo userInfo = userContextManager.getUserContext(request);
        if (userInfo != null) {
            UserContext.setUserInfo(userInfo);
            return true;
        }
        //返回认证失败
        responseOutWith401(response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private void responseOutWith401(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(401);
        try (PrintWriter out = response.getWriter()) {
            //将实体对象转换为JSON Object转换
            out.append(JSONUtil.toJsonStr(WebJson.data(RestEnum.LOGIN_INVALID)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
